package com.lagou.client;

import org.I0Itec.zkclient.ZkClient;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ClientBootStrap{

    //public static  final String providerName="UserService#sayHello#";
    public static void main(String[] args) throws InterruptedException {
        //zk 服务器父节点
        String parentNode="/lg-rpc-server";
        //1.创建zkclient
        ZkClient zkClient = new ZkClient("127.0.0.1:2181");
        System.out.println("会话被创建了..");


        // 获取子节点列表
        List<String> servers = zkClient.getChildren(parentNode);
        //创建线程池对象
        ExecutorService executor = Executors.newCachedThreadPool();

        //System.out.println(children);
        for (String server : servers) {
            System.out.println(server);
            startClientByZkNode(zkClient,executor,parentNode,server);
        }

        //注册监听事件
        LagouZkChildListener lagouZkChildListener = new LagouZkChildListener(servers,zkClient,executor,parentNode);
        zkClient.subscribeChildChanges(parentNode,lagouZkChildListener);

        Thread.sleep(Integer.MAX_VALUE);


    }

    /**
     * 根据zk节点信息启动netty客户端
     */
    public static void startClientByZkNode(ZkClient zkClient,ExecutorService executor,String parentNode,String server){
        String data = zkClient.readData(parentNode + "/" + server);
        String[] split = data.split(":");
        String hostname = split[0];
        Integer port = Integer.valueOf(split[1]);

        ClientStrap clientStrap = new ClientStrap(hostname, port);
        executor.submit(clientStrap);

    }

}
